package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.job.Content;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.util.CacheConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * 设备上传数据表Service业务层处理
 *
 * @author 小新IP归属中国
 * @date 2025-07-01
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void batchInsertDeviceData(Content content) {
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(ObjectUtil.isNotEmpty(content.getIotId()), Device::getIotId, content.getIotId()).eq(ObjectUtil.isNotEmpty(content.getProductKey()), Device::getProductKey, content.getProductKey()).eq(ObjectUtil.isNotEmpty(content.getDeviceName()), Device::getDeviceName, content.getDeviceName()));

        if (device == null) {
            return;
        }

        Map<String, Content.Item> items = content.getItems();
        if (items == null) throw new BaseException("远程数据异常");
        List<DeviceData> list = new ArrayList<>();
        items.forEach(new BiConsumer<String, Content.Item>() {
            @Override
            public void accept(String key, Content.Item value) {
                DeviceData deviceData = DeviceData.of().alarmTime(LocalDateTimeUtil.of(value.getTime())).deviceName(content.getDeviceName()).productKey(content.getProductKey()).iotId(content.getIotId()).nickname(device.getNickname()).functionId(key).accessLocation(device.getRemark()).locationType(device.getLocationType()).physicalLocationType(device.getPhysicalLocationType()).deviceDescription(device.getDeviceDescription()).dataValue(value.getValue() + "").productName(device.getProductName()).build();
                list.add(deviceData);
            }
        });
        saveBatch(list);
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, content.getIotId(), JSONUtil.toJsonStr(list));
    }

    /**
     * 查询设备上传数据表
     *
     * @param id 设备上传数据表主键
     * @return 设备上传数据表
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备上传数据表列表
     *
     * @param deviceData 设备上传数据表
     * @return 设备上传数据表
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto deviceData) {


        Page<DeviceData> page = page(Page.of(deviceData.getPageNum(), deviceData.getPageSize()), Wrappers.<DeviceData>lambdaQuery()
                .like(ObjectUtil.isNotEmpty(deviceData.getDeviceName()), DeviceData::getDeviceName, deviceData.getDeviceName()
                ).eq(ObjectUtil.isNotEmpty(deviceData.getFunctionId()), DeviceData::getFunctionId, deviceData.getFunctionId())
                .between(ObjectUtil.isAllNotEmpty(deviceData.getStartTime(), deviceData.getEndTime()), DeviceData::getAlarmTime, deviceData.getStartTime(), deviceData.getEndTime())
        );





        return getTableDataInfo(page);
    }

    /**
     * 新增设备上传数据表
     *
     * @param deviceData 设备上传数据表
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备上传数据表
     *
     * @param deviceData 设备上传数据表
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备上传数据表
     *
     * @param ids 需要删除的设备上传数据表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备上传数据表信息
     *
     * @param id 设备上传数据表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    private TableDataInfo getTableDataInfo(Page<DeviceData> page) {
        TableDataInfo<DeviceData> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(page.getRecords());
        dataInfo.setTotal(page.getTotal());
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setMsg("操作成功");
        return dataInfo;
    }

}
